import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:location_test/app/presentation/controllers/history_controller.dart';
import 'package:url_launcher/url_launcher.dart';

class HistoryView extends GetView<HistoryController> {
  const HistoryView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('定位历史轨迹'),
        actions: [
          // 使用 Obx 包裹，只有在有历史记录时才显示按钮
          Obx(() {
            if (controller.positionHistory.isNotEmpty) {
              return IconButton(
                icon: const Icon(Icons.timeline),
                tooltip: '在地图上显示完整轨迹',
                onPressed: () => _launchRouteInMap(controller.positionHistory),
              );
            }
            return const SizedBox.shrink();
          }),
          IconButton(
            icon: const Icon(Icons.delete_forever),
            tooltip: '清空历史记录',
            onPressed: () => _showClearConfirmationDialog(context),
          ),
        ],
      ),
      body: Obx(
        () {
          if (controller.positionHistory.isEmpty) {
            return const Center(
              child: Text(
                '暂无历史定位数据.\n请返回主页启动数据发送。',
                textAlign: TextAlign.center,
                style: TextStyle(color: Colors.grey),
              ),
            );
          }
          // 使用 .reversed 来显示最新的记录在最上面
          final history = controller.positionHistory.reversed.toList();
          return ListView.separated(
            itemCount: history.length,
            separatorBuilder: (context, index) => const Divider(height: 1),
            itemBuilder: (context, index) {
              final position = history[index];
              // 速度转换为 km/h
              final speedKmh = position.speed * 3.6;
              return ListTile(
                // 左侧显示序号
                leading: CircleAvatar(
                  backgroundColor: _getColorForSpeed(speedKmh),
                  child: Text(
                    '#${history.length - index}',
                    style: const TextStyle(
                        color: Colors.white, fontWeight: FontWeight.bold),
                  ),
                ),
                // 主标题显示经纬度
                title: Text(
                  '经: ${position.longitude.toStringAsFixed(6)}, '
                  '纬: ${position.latitude.toStringAsFixed(6)}',
                  style: const TextStyle(fontWeight: FontWeight.w500),
                ),
                // 副标题显示其他信息
                subtitle: Text(
                  '时间: ${DateFormat('HH:mm:ss').format(position.timestamp.toLocal())} | '
                  '速度: ${speedKmh.toStringAsFixed(1)} km/h | '
                  '海拔: ${position.altitude.toStringAsFixed(1)} m',
                ),
                // 右侧为地图按钮
                trailing: IconButton(
                  icon: const Icon(Icons.location_on_outlined),
                  tooltip: '在地图中打开此点',
                  onPressed: () => _launchPointInMap(position),
                ),
                dense: true,
              );
            },
          );
        },
      ),
    );
  }

  /// 根据速度返回不同的颜色，用于视觉提示
  Color _getColorForSpeed(double speedKmh) {
    if (speedKmh > 80) return Colors.red.shade400;
    if (speedKmh > 40) return Colors.orange.shade400;
    if (speedKmh > 5) return Colors.green.shade400;
    return Colors.blue.shade400;
  }

  /// 在地图应用中打开单个定位点
  void _launchPointInMap(Position position) {
    // 使用 geo URI scheme
    launchUrl(
      Uri.parse('geo:${position.latitude},${position.longitude}'),
      mode: LaunchMode.externalApplication,
    );
  }

  /// [新增] 尝试在地图应用中打开一条由所有点组成的路线
  void _launchRouteInMap(List<Position> history) {
    if (history.length < 2) {
      Get.snackbar('提示', '至少需要两个点才能规划路线。');
      return;
    }
    // 使用 Google Maps Directions API 的 URL 格式，这是最通用的
    // https://developers.google.com/maps/documentation/urls/get-started#directions-action
    final origin = history.first;
    final destination = history.last;
    final waypoints = history.sublist(1, history.length - 1);

    final url = Uri.https('www.google.com', '/maps/dir/', {
      'api': '1',
      'origin': '${origin.latitude},${origin.longitude}',
      'destination': '${destination.latitude},${destination.longitude}',
      'waypoints':
          waypoints.map((p) => '${p.latitude},${p.longitude}').join('|'),
      'travelmode': 'driving',
    });

    launchUrl(url, mode: LaunchMode.externalApplication);
  }

  void _showClearConfirmationDialog(BuildContext context) {
    Get.dialog(
      AlertDialog(
        title: const Text('清空历史记录'),
        content: const Text('确定要清空所有定位历史记录吗？'),
        actions: [ 
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              controller.clearHistory();
              Get.back();
            },
            child: const Text('清空'),
          ),
        ],
      ),
    );
  }
}